//
//  EGORefreshTableFooterView.m
//  Demo
//
//  Created by Devin Doty on 10/14/09October14.
//  Copyright 2009 enormego. All rights reserved.
//
//  Permission is hereby granted, free of charge, to any person obtaining a copy
//  of this software and associated documentation files (the "Software"), to deal
//  in the Software without restriction, including without limitation the rights
//  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//  copies of the Software, and to permit persons to whom the Software is
//  furnished to do so, subject to the following conditions:
//
//  The above copyright notice and this permission notice shall be included in
//  all copies or substantial portions of the Software.
//
//  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
//  THE SOFTWARE.
//

#import "EGORefreshTableFooterView.h"


#define TEXT_COLOR	 [UIColor colorWithRed:87.0/255.0 green:108.0/255.0 blue:137.0/255.0 alpha:1.0]
#define FLIP_ANIMATION_DURATION 0.18f


@interface EGORefreshTableFooterView ()
- (void)setState:(EGOPullRefreshState)aState;

@property (nonatomic, retain) UIScrollView *scrollView;

- (void)onScrollContentSizeChange:(UIScrollView *)scrollView;

@end

@implementation EGORefreshTableFooterView

@synthesize scrollView = _scrollView;

static int kObservingContentSizeChangesContext = 0;

- (void)startObservingContentSizeChangesInScrollView:(UIScrollView *)scrollView {
    [scrollView addObserver:self forKeyPath:@"contentSize" options:0 context:&kObservingContentSizeChangesContext];
}

- (void)stopObservingContentSizeChangesInScrollView:(UIScrollView *)scrollView {
    [scrollView removeObserver:self forKeyPath:@"contentSize" context:&kObservingContentSizeChangesContext];
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    if (context == &kObservingContentSizeChangesContext) {
		UIScrollView *scrollView = object;
		[self onScrollContentSizeChange:scrollView];
    } else {
        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
    }
}

- (void)onScrollContentSizeChange:(UIScrollView *)scrollView
{
	if (_state != EGOOPullRefreshLoading)
	{
		CGRect frame = self.frame;
		frame.origin.y = scrollView.contentSize.height;
		self.frame = frame;
		self.hidden = scrollView.bounds.size.height > scrollView.contentSize.height;
	}
}

- (id)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
		_lastUpdatedLabel.frame = CGRectMake(0.0f, 35.0f, self.frame.size.width, 20.0f);
		_statusLabel.frame = CGRectMake(0.0f, 17.0f, self.frame.size.width, 20.0f);
		_arrowImage.frame = CGRectMake(25.0f, 0.0f, 30.0f, 55.0f);
		_activityView.frame = CGRectMake(25.0f, 25.0f, 20.0f, 20.0f);

		_arrowImage.transform = CATransform3DMakeRotation(M_PI, 0.0f, 0.0f, 1.0f);;
    }
	
    return self;
	
}

#pragma mark -
#pragma mark Setters

- (void)setState:(EGOPullRefreshState)aState{
	
	switch (aState) {
		case EGOOPullRefreshPulling:
			
			_statusLabel.text = NSLocalizedString(@"松开即可加载更多...", @"Release to refresh status");
			[CATransaction begin];
			[CATransaction setAnimationDuration:FLIP_ANIMATION_DURATION];
			_arrowImage.transform = CATransform3DIdentity;
			[CATransaction commit];
			
			break;
		case EGOOPullRefreshNormal:
			
			if (_state == EGOOPullRefreshPulling) {
				[CATransaction begin];
				[CATransaction setAnimationDuration:FLIP_ANIMATION_DURATION];
				_arrowImage.transform = CATransform3DMakeRotation((M_PI / 180.0) * 180.0f, 0.0f, 0.0f, 1.0f);
				[CATransaction commit];
			}
			
			_statusLabel.text = NSLocalizedString(@"上拉即可加载更多...", @"Pull down to refresh status");
			[_activityView stopAnimating];
			[CATransaction begin];
			[CATransaction setValue:(id)kCFBooleanTrue forKey:kCATransactionDisableActions]; 
			_arrowImage.hidden = NO;
			_arrowImage.transform = CATransform3DMakeRotation((M_PI / 180.0) * 180.0f, 0.0f, 0.0f, 1.0f);
			[CATransaction commit];
			
			break;
		case EGOOPullRefreshLoading:
			
			_statusLabel.text = NSLocalizedString(@"加载中...", @"Loading Status");
			[_activityView startAnimating];
			[CATransaction begin];
			[CATransaction setValue:(id)kCFBooleanTrue forKey:kCATransactionDisableActions]; 
			_arrowImage.hidden = YES;
			[CATransaction commit];
			
			break;
		default:
			break;
	}
	
	_state = aState;
}

- (void)willMoveToSuperview:(UIView *)newSuperview
{
	if (self.scrollView)
	{
		[self stopObservingContentSizeChangesInScrollView:self.scrollView];
	}
	
	if ([newSuperview isKindOfClass:[UIScrollView class]])
	{
		self.scrollView = (UIScrollView *)newSuperview;
		[self startObservingContentSizeChangesInScrollView:self.scrollView];
	}
}

#pragma mark -
#pragma mark ScrollView Methods

- (void)egoRefreshScrollViewDidScroll:(UIScrollView *)scrollView {	

	if (self.hidden)
		return;
	
	CGFloat scrollPosition = scrollView.contentSize.height - scrollView.frame.size.height - scrollView.contentOffset.y;
	//NSLog(@"%f %f", scrollView.contentOffset.y, scrollPosition);
	
	if (_state == EGOOPullRefreshLoading) {
		
		//CGFloat offset = MAX(scrollView.contentOffset.y * -1, 0);
		//offset = MIN(offset, 60);
		//scrollView.contentInset = UIEdgeInsetsMake(-offset, 0.0f, 0.0f, 0.0f);
		
	} else if (scrollView.isDragging) {
		
		BOOL _loading = NO;
		if ([_delegate respondsToSelector:@selector(egoRefreshTableFooterDataSourceIsLoading:)]) {
			_loading = [_delegate egoRefreshTableFooterDataSourceIsLoading:self];
		}
		
		if (_state == EGOOPullRefreshPulling && scrollPosition > -65.0f && scrollPosition < 0.0f && !_loading) {
			[self setState:EGOOPullRefreshNormal];
		} else if (_state == EGOOPullRefreshNormal && scrollPosition < -65.0f && !_loading) {
			[self setState:EGOOPullRefreshPulling];
		}
		
//		if (scrollView.contentInset.top != 0) {
//			scrollView.contentInset = UIEdgeInsetsZero;
//		}
		
	}
	
}

- (void)egoRefreshScrollViewDidEndDragging:(UIScrollView *)scrollView {

	if (self.hidden)
		return;
	
	BOOL _loading = NO;
	if ([_delegate respondsToSelector:@selector(egoRefreshTableFooterDataSourceIsLoading:)]) {
		_loading = [_delegate egoRefreshTableFooterDataSourceIsLoading:self];
	}
	
	CGFloat scrollPosition = scrollView.contentSize.height - scrollView.frame.size.height - scrollView.contentOffset.y;
	
	if (scrollPosition <= -65.0f && !_loading) {
		
		[self setState:EGOOPullRefreshLoading];
		
		[UIView beginAnimations:nil context:NULL];
		[UIView setAnimationDuration:0.2];
		
		CGSize contentSize = scrollView.contentSize;
		scrollView.contentSize = CGSizeMake(contentSize.width, contentSize.height + self.bounds.size.height);

		[UIView commitAnimations];
        
        if ([_delegate respondsToSelector:@selector(egoRefreshTableFooterDidTriggerRefresh:)]) {
			[_delegate egoRefreshTableFooterDidTriggerRefresh:self];
		}
	}
	
}

- (void)egoRefreshScrollViewDataSourceDidFinishedLoading:(UIScrollView *)scrollView {	
	
	if (_state == EGOOPullRefreshLoading)
	{

	}
	
	[self setState:EGOOPullRefreshNormal];
	
	[self onScrollContentSizeChange:scrollView];

}


#pragma mark -
#pragma mark Dealloc

- (void)dealloc {

	if (self.scrollView)
	{
		[self stopObservingContentSizeChangesInScrollView:self.scrollView];
	}
	SAFE_RELEASE(_scrollView);
    [super dealloc];
}


@end
